<template>
  <view>
    <view class="form-item" @tap="onAvatarChange">
      <text class="label" style="color: red" v-if="isRequired">*</text>
      <text class="label">上传附件</text>
      <text
        class="dianwo"
        style="margin-left: 14rpx"
        v-if="!props.picturesPath.length"
        >请选择附件</text
      >
    </view>
    <view class="pictureClass" v-show="props.picturesPath.length">
      <view
        v-for="(picture, index) in props.picturesPath"
        :key="index"
        class="oneClass"
      >
        <text class="omitClass" @click="handlePreview(picture)">{{
          GetName(picture)
        }}</text
        ><text v-if="!isHide" @click="handleDelete(index)">X</text>
      </view>
    </view>
    <l-popup :radius="20" :show="popupShow">
      <image
        :src="imageUrl"
        mode="aspectFit"
        @click="popupShow = false"
        style="width: 100vh; height: 100vh"
      />
    </l-popup>
  </view>
</template>

<script setup>
import lPopup from "@/uni_modules/l-popup/components/l-popup/l-popup.vue";
import { baseURL } from "@/utils";
const props = defineProps([
  "picturesPath",
  "key",
  "formObj",
  "isHide",
  "isRequired",
]);
const popupShow = ref(false);
const imageUrl = ref("");
// 文件上传-兼容小程序端、H5端、App端
const uploadFile = (filePath) => {
  // 文件上传
  uni.uploadFile({
    url: "/upload_file",
    name: "file",
    filePath,
    fileType: "image",
    success: (res) => {
      const result = JSON.parse(res.data);
      if (result.code === 200) {
        const avatar = result.data?.filePath.replaceAll("\\", "//") || "";
        props.picturesPath.push(avatar);
        uni.showToast({ icon: "success", title: "上传成功" });
      } else {
        uni.showToast({ icon: "error", title: "出现错误" });
      }
    },
  });
};
const onAvatarChange = () => {
  if (!props.isHide) {
    uni.chooseImage({
      count: 5,
      sizeType: ["original"],
      sourceType: ["album", "camera"],
      success: (res) => {
        // 本地路径
        res.filePaths.forEach((tempFilePath) => {
          uploadFile(tempFilePath);
        });
      },
    });
  }
};

const GetName = computed(() => {
  return (picture) => {
    const lists = picture.split("//");
    return lists[lists.length - 1];
  };
});
const handleDelete = (index) => {
  props.picturesPath.splice(index, 1);
};
const handlePreview = (picture) => {
  uni.previewImage({
    urls: [baseURL + "/show_img?filePath=" + picture],
    indicator: "number",
  });
};
</script>

<style lang="scss" scoped>
.form-item {
  display: flex;
  height: 96rpx;
  line-height: 46rpx;
  padding: 25rpx 10rpx;
  background-color: #fff;
  font-size: 28rpx;
  border-bottom: 1rpx solid #ddd;
}
</style>